package be.vsko.zelfevaluatie.rest;

import java.util.Iterator;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;

import be.vsko.zelfevaluatie.help.QueryParameters;

public class RoaServlet {
	public static final int DEFAULT_LIMIT = 50;
	@Context
	protected HttpServletRequest request;
	@Context
	protected HttpServletResponse response;
	
	public String getHref(String url) {
		System.out.println(request.getRequestURL());
		System.out.println(request.getRequestURI());
		System.out.println(request.getContextPath());
		System.out.println(request.getQueryString());
		System.out.println(request.getServletPath());
		System.out.println(request.getPathInfo());
		return request.getRequestURL()+url;
	}
	
	public String getMetaHref(boolean next, QueryParameters query) {
		String href = request.getRequestURL()+request.getRequestURI()+"?offset=";
		if(next) {
			href += query.getOffset()+query.getLimit();
		} else {
			int newOffset = query.getOffset()-query.getLimit();
			newOffset = newOffset < 0 ? 0 : newOffset;
			href += newOffset;
		}
		if(query.getLimit() != DEFAULT_LIMIT)
			href += "&limit="+query.getLimit();
		if(!query.getOrderBy().equals(query.getOrderByDefault()))
			href += "&orderby="+query.getOrderBy();
		if(query.isDescending())
			href += "&descending=true";
		Iterator<Entry<String, String>> it = query.getFilters().entrySet().iterator();
	    while (it.hasNext()) {
	        Entry<String, String> pairs = it.next();
	        if(!pairs.getValue().equals(""))
	        	href += "&"+pairs.getKey()+"="+pairs.getValue();
	    }
		return href;
	}
}
